import java.util.LinkedList;
import java.util.Queue;
import edu.purdue.cs.cs180.channel.Channel;

/**
 * project7
 *
 * brief description of the program
 *
 * This program is released to public domain according to
 * author's wish, you can view full license at
 * http://tomatoeskit.org/upload/PublicDomainLicense.txt
 *
 * @author Fangning CHENG (Alpha.L Cheng) <chengf@purdue.edu>
 *
 * @lab section number 
 *
 * @date Nov 8, 2013
 *
 */

public class FCFSServer extends Server {
    Queue<EndPointInfo> requesters = new LinkedList<EndPointInfo>();
    Queue<EndPointInfo> volunteers = new LinkedList<EndPointInfo>();
    
    
    public FCFSServer(Channel cnl) {
        super(cnl);
        System.err.println("\tFCFS Server is running ...");
    }

    @Override
    public void messageReceived(String message, int clientID) {       
        String msg[] = message.split("\\s+");
        int msgLen = msg.length;

        System.err.println(String.format("\t\tMessage from %d: %s", clientID, message));
        
        // Invalid message
        if (msgLen < 2)
            return;

        // Request message
        if (msg[0].equals("REQUEST")) {
            if (msgLen < 3) {
                System.err.println("\t\t\tBroken REQUEST message");
                return;
            }
            requesters.offer(new EndPointInfo(msg[1], clientID, msg[2]));
            System.err.println(String.format("\t\t\tRequester %d added to Queue", clientID));
        }

        // Volunteer message
        if (msg[0].equals("VOLUNTEER")) {
            volunteers.offer(new EndPointInfo(msg[1], clientID));
            System.err.println(String.format("\t\t\tVolunteer %d added to Queue", clientID));
        }

        // Process the queue
        processQueue();
    }

    private void processQueue() {
        int loopCount = volunteers.size() < requesters.size() ? volunteers.size() : requesters.size();
        // Redundant, provides flexibility in case code changes in later days.
        // Should always be 1 at this time
        
        for (int i = 0; i < loopCount; ++i) {
            EndPointInfo requester = requesters.poll();
            EndPointInfo volunteer = volunteers.poll();
            
            sendMessages(volunteer.clientID, requester.clientID, 
                    timeTable.get(volunteer.building).get(requester.building), 
                    requester.building, requester.urgency, volunteer.building);
        }
    }
}
